import axios from 'axios'
import API_ENV, { apiBase } from './api_env'
import { Loading, Message } from 'element-ui'

// 设置请求超时时间
const TIMEOUT = 6000

// axios基本配置
let request = axios.create({
    // 当前请求为跨域类型时是否在请求中协带cookie
    withCredentials: true,
    timeout: TIMEOUT,
})

// 定义loading变量
let loading

//使用Element loading-start 方法
function startLoading() {
    loading = Loading.service({
        lock: true,
        text: '加载中',
        background: 'rgba(0, 0, 0, 0)',
    })
}

//使用Element loading-close 方法
function endLoading() {
    loading.close()
}

let needLoadingRequestCount = 0
export function showFullScreenLoading() {
    if (needLoadingRequestCount === 0) {
        startLoading()
    }
    needLoadingRequestCount++
}

export function tryHideFullScreenLoading() {
    if (needLoadingRequestCount <= 0) return
    needLoadingRequestCount--
    if (needLoadingRequestCount === 0) {
        endLoading()
    }
}

// request 请求拦截器
request.interceptors.request.use(
    (config) => {
        // const { token } = store.state
        const token = '123'
        config.headers['token'] = token
        showFullScreenLoading()

        return config
    },
    (error) => {
        return Promise.reject(error)
    }
)

// request 响应拦截器
request.interceptors.response.use(
    (response) => {
        tryHideFullScreenLoading()
        const { date } = response.headers //以服务器响应时间为准
        store.commit('UPDATE_DATE', date || new Date())
        if (response.data.code == '401') {
            store.commit('UPDATE_TOKEN', {
                token: '',
            })

            store.commit('UPDATE_LOGIN', {
                token: false,
            })

            store.commit('UPDATE_USER_INFO', {})

            store.commit('UPDATE_LOGOUT')

            if (router.currentRoute.meta.requireAuth) {
                store.commit('UPDATE_LOGIN_POPUP')
            }
        }
        if (!response.data.success) {
            if (whiteListUrl.indexOf(response.config.url) < 0 && response.data.code != '401' && response.data.message) {
                Message.error(response.data.message)
            }
        }
        return response
    },
    (error) => {
        tryHideFullScreenLoading()
        let msg = error.message || '网络繁忙，请稍后再试'
        if (msg.indexOf('timeout') > -1) {
            msg = '网络繁忙，请稍后再试'
        }
        Message.error(msg)
        return Promise.reject(error)
    }
)

/**
 * 封装get方法
 * @param url
 * @param params
 * @param isFullRes
 * @returns {Promise<any>}
 */

export function fetch(url, params = {}, isFullRes) {
    return new Promise((resolve, reject) => {
        request
            .get(url, {
                params: params,
            })
            .then((response) => {
                if (response.data.success) {
                    return resolve(isFullRes ? response.data : response.data.result)
                } else {
                    return reject(response.data)
                }
            })
            .catch((err) => {
                reject(err)
            })
    })
}

/**
 * 封装post请求
 * @param url
 * @param data
 * @param isJavaApi
 * @param options
 * @returns {Promise}
 */

export function post(url, data = {}, isJavaApi, options) {
    return new Promise((resolve, reject) => {
        request.get(url, data, options).then(
            (response) => {
                if (response.data.success) {
                    return resolve(response.data.result)
                } else {
                    return reject(response.data)
                }
            },
            (err) => {
                reject(err)
            }
        )
    })
}

/**
 * 封装put请求
 * @param url
 * @param data
 * @param isJavaApi
 * @returns {Promise}
 */

export function put(url, data = {}, isJavaApi) {
    return new Promise((resolve, reject) => {
        request.put(url, data).then(
            (response) => {
                if (response.data.success && response.data.result) {
                    return resolve(response.data.result)
                } else {
                    return reject(response.data)
                }
            },
            (err) => {
                reject(err)
            }
        )
    })
}

export { apiBase } from './api_env'
